package ktarou.m1k4.icu.handler;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import ktarou.m1k4.icu.util.HTMLUtil;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class UploadHandler {
	private String strURL = "http://upload.indowebster.com/login.php";
	private String strUPL = "";
	private String uplURL = "";
	private String post_url = "";
	private String UPLOAD_IDENTIFIER = "";
	private String USER_ID = "";
	private HttpState initialState;
	private Cookie mycookie;
	private HttpClient httpclient = new HttpClient();
	private int result = 0;
	private Cookie[] cookies;
	private String username;
	private String password;
	private static UploadHandler instance = null;

	public static UploadHandler getInstance() {
		if (instance == null) {
			instance = new UploadHandler();
		}
		return instance;
	}

	private UploadHandler() {
		// Get target URL
		System.out.println("Target URL: " + strURL);

		// Get initial state object
		initialState = new HttpState();

		// Initial set of cookies can be retrieved from persistent storage
		// and re-created, using a persistence mechanism of choice,
		mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null,
				false);

		// and then added to your HTTP state instance
		initialState.addCookie(mycookie);

		// Get HTTP client instance

		httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(
				30000);
		httpclient.setState(initialState);

		// RFC 2101 cookie management spec is used per default
		// to parse, validate, format & match cookies
		httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

	}

	public static void printTheCookies(Cookie[] cookies) {
		System.out.println("Present cookies: ");
		for (int i = 0; i < cookies.length; i++) {
			System.out.println(" - " + cookies[i].toExternalForm());
		}

	}

	public void cekConnection() {
		GetMethod get = new GetMethod(strURL);

		try {
			result = httpclient.executeMethod(get);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("First Response status code: " + result
				+ HttpStatus.getStatusText(result));
		cookies = httpclient.getState().getCookies();
		printTheCookies(cookies);

		get.releaseConnection();
	}

	public boolean login() {
		boolean valid = false;
		cekConnection();
		PostMethod post = new PostMethod(strURL);
		NameValuePair[] data = { new NameValuePair("username", username),
				new NameValuePair("password", password),
				new NameValuePair("go", "Login") };
		post.setRequestBody(data);

		// Execute HTTP GET
		try {
			result = httpclient.executeMethod(post);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Display status code
		System.out.println("Second Response status code: " + result
				+ HttpStatus.getStatusText(result));
		httpclient.getState().getCookies();
		printTheCookies(cookies);
		Header locationHeader = post.getResponseHeader("location");
		if (locationHeader != null) {
			System.out.println("redirect to " + locationHeader.getValue());
			strUPL = locationHeader.getValue();
			valid = true;
		}
		post.releaseConnection();
		if (valid) {
			setup();
		}
		return valid;
	}
	private void setup(){
		GetMethod get = new GetMethod(strUPL);

		try {
			result = httpclient.executeMethod(get);
			String strTMP = get.getResponseBodyAsString();
			HTMLUtil util = HTMLUtil.getInstance();
			util.prosesHTML(strTMP);
			String[] tmpVAL = util.getUploadIdentifier();
			setUPLOAD_IDENTIFIER(tmpVAL[0]);
			setUSER_ID(tmpVAL[1]);
			post_url = tmpVAL[2];
			uplURL = tmpVAL[3];
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public boolean upload(Map<String, String> value) {
		boolean ok = false;
		File targetFile = new File(value.get("file"));
		NameValuePair[] data = { new NameValuePair("cat_selector", value.get("cat_selector")),
				new NameValuePair("file_desc", targetFile.getName()),
				new NameValuePair("file_title", targetFile.getName()),
				new NameValuePair("UPLOAD_IDENTIFIER", UPLOAD_IDENTIFIER),
				new NameValuePair("post_url", post_url),
				new NameValuePair("radio2", "on"),
				new NameValuePair("action1", "upload"),
				new NameValuePair("user_id", USER_ID)};
		PostMethod filePost = new PostMethod(uplURL);
		//filePost.setRequestBody(data);
		filePost.getParams().setBooleanParameter(
				HttpMethodParams.USE_EXPECT_CONTINUE, true);
		try {

			/*Part[] parts = { new FilePart(targetFile.getName(), targetFile) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts,
					filePost.getParams()));*/
			filePost.setRequestEntity(new FileRequestEntity(targetFile,"utf-8"));
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(
					5000);
			System.out.println("Uploading "+data[0].toString());
			System.out.println("Uploading "+data[1].toString());
			System.out.println("Uploading "+data[2].toString());
			System.out.println("Uploading "+data[3].toString());
			System.out.println("Uploading "+uplURL);
			int status = httpclient.executeMethod(filePost);
			/*Header locationHeader = filePost.getResponseHeader("location");
			System.out.println(locationHeader.getValue());*/
			httpclient.getState().getCookies();
			printTheCookies(cookies);
			if (status == HttpStatus.SC_OK) {
				System.out.println("Upload complete, response="
						+ filePost.getResponseBodyAsString());
			} else {
				System.out.println("Upload failed, response="
						+ HttpStatus.getStatusText(status));
			}
		} catch (Exception ex) {
			System.out.println("ERROR: " + ex.getClass().getName() + " "
					+ ex.getMessage());
			ex.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
		return ok;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUPLOAD_IDENTIFIER(String uPLOAD_IDENTIFIER) {
		UPLOAD_IDENTIFIER = uPLOAD_IDENTIFIER;
	}

	public String getUPLOAD_IDENTIFIER() {
		return UPLOAD_IDENTIFIER;
	}

	public void setUSER_ID(String uSER_ID) {
		USER_ID = uSER_ID;
	}

	public String getUSER_ID() {
		return USER_ID;
	}

}
